﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Security.Principal;
using System.Text;
using System.Threading.Tasks;

namespace VAELinker.Utils
{
    public static class ElevateUtil
    {
        static bool? isRunningAsAdministrator = null;
        public static bool IsRunningAsAdministrator
        {
            get
            {
                if(!isRunningAsAdministrator.HasValue)
                {
                    isRunningAsAdministrator = RunningAsAdministrator();
                }
                return isRunningAsAdministrator.Value;
            }
        }

        private static bool RunningAsAdministrator()
        {
            WindowsIdentity identity = WindowsIdentity.GetCurrent();
            WindowsPrincipal principal = new WindowsPrincipal(identity);
            return principal.IsInRole(WindowsBuiltInRole.Administrator);
        }

        public static void RunAsAdmin(string args = "")
        {
            try
            {
                var exeName = Process.GetCurrentProcess().MainModule.FileName;
                ProcessStartInfo startInfo = new ProcessStartInfo(exeName, args)
                {
                    Verb = "runas",
                    UseShellExecute = true
                };
                Process.Start(startInfo);
            }
            catch (Exception) { /* Ignored */ }
        }
    }
}
